package com.wchen.project.zk.demo;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

/**
 * @Desc:   使用包含权限信息的 Zookeeper 会话创建数据节点
 * @author: cww
 * @DateTime: 2020/1/19 19:34
 */

public class ZooKeeperAuthAPI implements Watcher {
    final static String PATH = "/zk-book-auth_test";
    private static CountDownLatch connectedSemaphore = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        ZooKeeper zooKeeper = new ZooKeeper("home:2181", 5000, new ZooKeeperAuthAPI());
        connectedSemaphore.await();
//        zooKeeper.create(PATH + "1", "init1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

        // 使用 digest 模式添加权限，为当前这次会话进行添加权限
        zooKeeper.addAuthInfo("digest", "foo:true".getBytes());
        zooKeeper.create(PATH, "init".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);
        // 对上面添加了权限控制的进行读取就会报： KeeperErrorCode = NoAuth for /zk-book-auth_test 错误
//        ZooKeeper zooKeeper1 = new ZooKeeper("home:2181", 5000, null);
//        zooKeeper1.getData(PATH, false, null);

        // 若使用错误的权限信息开启会话，查询也会报同样错
        ZooKeeper zooKeeper2 = new ZooKeeper("home:2181", 5000, new ZooKeeperAuthAPI());
        zooKeeper2.addAuthInfo("digest", "foo:true".getBytes());
        zooKeeper2.getData(PATH, false, null);
        Thread.sleep(50000);
    }

    @Override
    public void process(WatchedEvent event) {
        if (Event.KeeperState.SyncConnected == event.getState()) {
            if (Event.EventType.None == event.getType() && null == event.getPath()) {
                connectedSemaphore.countDown();
            }
        }
    }
}
